package com.example.videoplayer.service.impl;

import com.example.videoplayer.model.User;
import com.example.videoplayer.repository.UserRepository;
import com.example.videoplayer.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

@Service
public class AuthServiceImpl implements AuthService {
    private static final Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Mono<User> authenticate(String username, String password) {
        return userRepository.findActiveUserByUsername(username)
                .flatMap(user -> {
                    if (passwordEncoder.matches(password, user.getPassword())) {
                        logger.debug("Password match successful for user: {}", username);
                        return Mono.just(user);
                    }
                    logger.debug("Password match failed for user: {}", username);
                    return Mono.error(new BadCredentialsException("Invalid password"));
                })
                .switchIfEmpty(Mono.error(new BadCredentialsException("User not found")))
                .doOnError(e -> logger.error("Authentication error for user {}: {}", username, e.getMessage()));
    }

    @Override
    public Mono<Void> logout() {
        // 在这里可以添加任何必要的注销逻辑
        return Mono.empty();
    }
} 